package com.android.equipment.utils;

import android.app.Activity;
import android.graphics.Rect;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;

public class KeyBoardHelperUtil {
    private Activity activity;
    private OnKeyBoardStatusChangeListener onKeyBoardStatusChangeListener;
    private int screenHeight;
    private int blankHeight = 0;

    public KeyBoardHelperUtil (Activity activity) {
        this.activity = activity;
        //屏幕分辨率的绝对高度
        screenHeight = activity.getResources().getDisplayMetrics().heightPixels;
        //根据输入法调整View移动
        activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        //获取当前activiy的view
        View content = activity.findViewById(android.R.id.content);
        content.getViewTreeObserver().addOnGlobalLayoutListener(onGlobalLayoutListener);
    }

    private ViewTreeObserver.OnGlobalLayoutListener onGlobalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            //Rect 其实就是左上右下
            Rect rect = new Rect();
            //获取当前窗口可视区域大小的
            activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
            int keyboardHeight = screenHeight - rect.bottom;
            if (keyboardHeight != blankHeight) {//软键盘高度和上一次高度比较,首次blankHeight =0
                if (keyboardHeight > blankHeight) {//说明弹出软键盘
                    // keyboard pop
                    if (onKeyBoardStatusChangeListener != null) {
                        onKeyBoardStatusChangeListener.OnKeyBoardShow(keyboardHeight);
                    }
                } else { // newBlankheight < blankHeight 或者 newBlankheight = blankHeight
                    //说明隐藏软键盘
                    if (onKeyBoardStatusChangeListener != null) {
                        onKeyBoardStatusChangeListener.OnKeyBoardHidden(blankHeight);
                    }
                }
            }
            blankHeight = keyboardHeight;
        }
    };



    public void setOnKeyBoardStatusChangeListener(OnKeyBoardStatusChangeListener onKeyBoardStatusChangeListener) {
        this.onKeyBoardStatusChangeListener = onKeyBoardStatusChangeListener;
    }


    public interface OnKeyBoardStatusChangeListener {

        void OnKeyBoardShow(int height);

        void OnKeyBoardHidden(int height);
    }

    public void onDestory() {
        View content = activity.findViewById(android.R.id.content);
        content.getViewTreeObserver().removeOnGlobalLayoutListener(onGlobalLayoutListener);
    }
}
